<template>
	<view class="container" @touchstart="touchStart" @touchend="touchEnd">
		<!-- 固定的类目栏 -->
		<view class="fixed-category">
			<scroll-view scroll-x="true" class="scroll-content" :scroll-into-view="scrollIntoView"
				:scroll-with-animation="true">
				<view v-for="(tab, index) in tabs" :key="index" class="scroll-item" @tap="handleTabClick(tab.id)"
					:id="`tab${tab.id}`">
					<text :class="topBarIndex === tab.id ? 'f-active-color' : 'f-color'">{{ tab.name }}</text>
				</view>
			</scroll-view>
			<tn-button style="margin-left: 88%;" :plain="true" :border="false" shape="icon" :fontBold="true"
				@click="CategorysShow=true">
				<text class="tn-icon-down" />
			</tn-button>
			<tn-popup v-model="CategorysShow" mode="top" style="margin-top: 35%;">
				<view style="width: 100%;">
					<tn-button v-for="(tab) in tabs" :key="tab.id" style="border: 1px solid black; margin: 2px;"
						@click="handleTabClick(tab.id)">{{tab.name}}</tn-button>
				</view>
			</tn-popup>
		</view>

		<!-- z-paging 内容区 -->
		<z-paging ref="paging" v-model="showList" @query="queryList" :fixed="false" :auto-height="true"
			:refresher-enabled="true" :loading-more-enabled="true" :auto-show-back-to-top="true"
			:safe-area-inset-bottom="false" :loading-more-offset="200" :back-to-top-bottom="500"
			:back-to-top-right="40">
			<view class="products-grid">
				<view v-for="(item, index) in showList" :key="index" class="item-container" @click="dian(item.id)">
					<image :src="item.picUrl || '/static/5c750d6f977fe.png'" class="item-image" />
					<text>{{ item.name }}</text>
				</view>
			</view>
		</z-paging>
	</view>
</template>

<script>
	export default {
		name: "Product",
		props: {
			tabBar: {
				type: String,
				default: ""
			},
			show: {
				type: Function,
				default: null
			},
			city: {
				type: String,
				default: ""
			}
		},
		data() {
			return {
				CategorysShow: false,
				scrollIntoView: "tab1036007",
				tabs: [],
				topBarIndex: 1036007,
				showList: [],
				pageHeight: '100vh',
				pageNo: 0,
				pageSize: 0,
				touchStartX: 0,
				touchEndX: 0,
				companyInfo: {},
				locationCity: ""
			}
		},
		mounted() {
			this.getCompanyInfo()
			this.locationCity = this.city
		},
		methods: {
			getCompanyInfo() {
				const userInfo = uni.getStorageSync('userInfo');
				let that = this;

				// 检查是否有用户信息和用户ID
				if (userInfo && userInfo.id) {
					const userId = userInfo.id;
					uni.request({
						url: this.baseUrl + "/wx/companyInfo/getCompanyInfo",
						method: 'GET',
						data: {
							userId
						},
						success: (res) => {
							if (res.statusCode === 200 && res.data.errno === 0 && res.data.data) {
								that.companyInfo = res.data.data;
								// 获取公司信息后再获取类目列表
								that.getCategoryList();
							} else {
								// 获取公司信息失败，也尝试获取类目列表
								that.getCategoryList();
							}
						},
						fail: (error) => {
							console.error('获取公司信息失败:', error);
							// 即使获取公司信息失败，也尝试获取类目列表
							that.getCategoryList();
						}
					});
				} else {
					// 没有用户ID，直接获取所有类目
					that.getCategoryList();
				}
			},

			getNavBarHeight() {
				const systemInfo = uni.getSystemInfoSync()
				const navBarHeight = (systemInfo.statusBarHeight || 0) + 140
				return navBarHeight
			},
			getCategoryList() {
				uni.request({
					url: this.baseUrl + "/admin/category/list",
					success: (res) => {
						if (res.data.errno === 0 && res.data.data.list) {
							// 检查公司是否有类目信息
							if (this.companyInfo && this.companyInfo.categoryId) {
								// 使用公司的类目ID
								const companyCategoryId = parseInt(this.companyInfo.categoryId);

								// 在所有类目中查找公司的类目
								let foundCategory = null;

								// 先在顶级类目中查找
								foundCategory = res.data.data.list.find(item => item.id === companyCategoryId);

								if (foundCategory) {
									// 如果是顶级类目，只显示这一个类目
									this.tabs = [foundCategory];
								} else {
									// 在子类目中查找
									for (let category of res.data.data.list) {
										if (category.children) {
											foundCategory = category.children.find(child => child.id ===
												companyCategoryId);
											if (foundCategory) {
												// 只显示公司的这一个类目
												this.tabs = [foundCategory];
												break;
											}
										}
									}
								}
							} else {
								// 如果公司没有类目信息，则显示所有类目
								let defaultCategory = res.data.data.list.find(item => item.id === 1036065);
								if (defaultCategory && defaultCategory.children) {
									this.tabs = defaultCategory.children;
								}
							}

							// 如果有类目，设置默认选中第一个
							if (this.tabs.length > 0) {
								this.topBarIndex = this.tabs[0].id;
								this.scrollIntoView = `tab${this.topBarIndex}`;

								// 延迟加载商品列表，确保UI已更新
								setTimeout(() => {
									this.$refs.paging && this.$refs.paging.reload();
								}, 100);
							}
						}
					},
					fail(e) {
						console.log('获取类目列表失败:', e);
					}
				});
			},
			handleTabClick(index) {
				if (index !== this.topBarIndex) {
					this.topBarIndex = index;
					this.scrollIntoView = `tab${index}`;
					this.CategorysShow = false;
					this.$refs.paging.reload();
				}
			},
			queryList(pageNo, pageSize) {
				this.pageNo = pageNo
				this.pageSize = pageSize
				let url = ""
				if (this.locationCity === "") {
					url = `${this.baseUrl}/admin/goods/list`
				} else {
					url = `${this.baseUrl}/wx/goods/listByLocationCity`
				}
				const categoryId = this.topBarIndex;
				uni.request({
					url: url,
					data: {
						page: pageNo,
						limit: pageSize,
						sort: 'add_time',
						order: 'desc',
						categoryId: categoryId,
						locationCity: this.locationCity
					},
					success: (res) => {
						if (res.data.errno === 0) {
							this.$refs.paging.complete(res.data.data.list);
						} else {
							this.$refs.paging.complete([]);
						}
					},
					fail: () => {
						this.$refs.paging.complete([]);
					}
				});
			},
			dian(id) {
				uni.navigateTo({
					url: "/pages/index/productDetails/productDetails?id=" + id
				})
			},
			getInfoName(searchValue) {
				let url = "";
				if (this.locationCity === "") {
					url = `${this.baseUrl}/admin/goods/list`
				} else {
					url = `${this.baseUrl}/wx/goods/listByLocationCity`
				}
				const categoryId = this.topBarIndex;
				uni.request({
					url: url,
					data: {
						page: this.pageNo,
						limit: this.pageSize,
						name: searchValue,
						sort: 'add_time',
						order: 'desc',
						categoryId: categoryId,
						locationCity:this.locationCity
					},
					success: (res) => {
						if (res.data.errno === 0) {
							const goodsList = res.data.data.list;
							this.show(`找到 ${goodsList.length} 个结果`);

							if (res.data.errno === 0) {
								this.$refs.paging.complete(goodsList);
							} else {
								this.$refs.paging.complete([]);
							}
						}
					}
				});
			},
			touchStart(e) {
				const touch = e.touches[0];
				const touchY = touch.clientY;
				if (touchY > 250) {
					this.touchStartX = touch.clientX;
				}
			},
			touchEnd(e) {
				if (!this.touchStartX) return;
				this.touchEndX = e.changedTouches[0].clientX;
				const moveX = this.touchEndX - this.touchStartX;
				if (Math.abs(moveX) > 135) {
					const currentIndex = this.tabs.findIndex(tab => tab.id === this.topBarIndex);
					if (moveX > 0 && currentIndex > 0) {
						this.handleTabClick(this.tabs[currentIndex - 1].id);
					} else if (moveX < 0 && currentIndex < this.tabs.length - 1) {
						this.handleTabClick(this.tabs[currentIndex + 1].id);
					}
				}
				this.touchStartX = 0;
			}
		}
	};
</script>

<style>
	@import '../../static/mengyuan/stylesheet.css';

	.container {
		position: relative;
		width: 100%;
		height: 100vh;
		padding-top: 60rpx;
	}

	.scroll-content {
		width: 100%;
		white-space: nowrap;
	}

	.scroll-item {
		display: inline-block;
		padding: 10rpx 20rpx;
		font-size: 30rpx;
	}

	.f-active-color {
		padding: 10rpx 0;
		border-bottom: 8rpx solid #01BEFF;
		color: #70dbff;
	}

	.f-color {
		color: #ffffff;
	}

	.item-container {
		width: 120px;
		height: 250px;
		display: inline-block;
		margin: 20px 0 0 10%;
		border-radius: 30px;
		text-align: center;
		margin-bottom: 20rpx;
	}

	.item-image {
		height: 70%;
		width: 120px;
		border-radius: 30px 30px 0 0;
	}

	.products-grid {
		padding: 20rpx;
		padding-top: 20rpx;
		padding-bottom: 240rpx;
	}

	.fixed-category {
		position: fixed;
		top: 200rpx;
		left: 0;
		right: 0;
		z-index: 999;
		background-color: #008080;
		padding: 10rpx 0;
	}
</style>